package com.kevin.permission.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.kevin.permission.common.RequestHolder;
import com.kevin.permission.dao.SysRoleUserMapper;
import com.kevin.permission.dao.SysUserMapper;
import com.kevin.permission.model.SysRoleUser;
import com.kevin.permission.model.SysUser;
import com.kevin.permission.util.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class SysRoleUserService {

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    public void changeRoleUsers(int roleId, List<Integer> userIdList) {
        List<Integer> orignUserIdList=sysRoleUserMapper.getUserIdListByRoleId(roleId);
        if (orignUserIdList.size()==userIdList.size()){
            Set<Integer> originUserIdSet= Sets.newHashSet(orignUserIdList);
            Set<Integer> userIdSet=Sets.newHashSet(userIdList);
            originUserIdSet.removeAll(userIdSet);
            if (CollectionUtils.isEmpty(originUserIdSet)){
                return;
            }
        }
        updateRoleUsers(roleId,userIdList);
    }

    private void updateRoleUsers(int roleId, List<Integer> userIdList) {
        sysRoleUserMapper.deleteByRoleId(roleId);

        if (CollectionUtils.isEmpty(userIdList)){
            return;
        }
        List<SysRoleUser> roleUserList=Lists.newArrayList();
        for (Integer userId:userIdList){
            SysRoleUser roleUser=SysRoleUser.builder().roleId(roleId).userId(userId).operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new Date()).build();
            roleUserList.add(roleUser);
        }
        sysRoleUserMapper.batchInsert(roleUserList);

    }


    public List<SysUser> getListByRoleId(int roleId) {
        List<Integer> userIdList=sysRoleUserMapper.getUserIdListByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)){
            return Lists.newArrayList();
        }
        return sysUserMapper.getByIdList(userIdList);
    }
}
